//
//  LFDBManager.m
//  doubleVideo
//
//  Created by 火力全开 on 15/10/18.
//  Copyright © 2015年 lin. All rights reserved.
//

#import "LFDBManager.h"
#import "FMDatabase.h"
#import "DataModel.h"
@interface LFDBManager()<NSCopying>
{
    FMDatabase *_db;
}

@end
@implementation LFDBManager
static id _instace;
+(instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [[self alloc] init];
    });
    return _instace;
}



-(id)copyWithZone:(NSZone *)zone
{
    return _instace;
}


+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [super allocWithZone:zone];
    });
    return _instace;
}

-(id)init
{
    self = [super init];
    if (self) {
        
        NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/LiTingFeng.db"];
        NSLog(@"DB Path%@",path);
        //创建并打开
        _db = [FMDatabase databaseWithPath:path];
        if ([_db open]) {
           NSLog(@"创建成功");
            //打开成功
          NSString *sql = @"create table tableName(name  text primary key not NULL ,useNumber INTEGER not NULL,lastTime Date not NULL,cycle INTEGER not NULL)";
            BOOL isSuccess = [_db executeUpdate:sql];
            if (!isSuccess) {
                NSLog(@"创建表失败:%@~~~",_db.lastErrorMessage);
            }
        }else
        {
            NSLog(@"创建数据库或打开失败");
        }
    }
    return self;
}


//写入数据
-(void)insertData:(id)object{
    
    if ([object isKindOfClass:[CommenModel class]]) {
        
        CommenModel * model = (CommenModel *)object;
        
        if ([_db open]) {
            
            NSString *insertSql= [NSString stringWithFormat:@"INSERT INTO tableName (name, useNumber, lastTime,cycle) VALUES ('%@', '%lu', '%@','%lu')",model.name, (unsigned long)model.useNumber ,model.lastTime,(unsigned long)model.cycle];
            
            BOOL isSuccess = [_db executeUpdate:insertSql];
            
            if (!isSuccess) {
                NSLog(@"error when insert db table");
            } else {
                NSLog(@"success to insert db table");
            }
            
            [_db close];
            
            
        }
    }
    



}



//是更新还是写入数据
-(void)updataOrInsertWithName:(CommenModel*)model{
    NSArray * nameArray = [self fetchAllName];
    if ([nameArray containsObject:model.name]) {
        [self isUpdataOrNotWithTime:model];
        
    }else{
        [self insertData:model];
    
    
    }

}



//设立时间戳
-(void)isUpdataOrNotWithTime:(CommenModel*)model{
    NSDate * timeString = model.lastTime;

    NSDate *  nowDate = [NSDate date];
    NSTimeInterval   distanceBetweenDates = [nowDate timeIntervalSinceDate:timeString];
    if (distanceBetweenDates > [model.time floatValue]/2) {
        [self updauseNumberWithModel:model];
        [self updaTimeWithModel:model];
    }
}

//根据课程名更新使用次数
-(void)updauseNumberWithModel:(CommenModel*)model{
    
    CommenModel * data  = [self fetchDataWithName:model.name];
    
    if (data.useNumber == [model.period intValue ] - 1) {
        
        [self updacycleWithModel:model];
        
        if ([_db open]) {
            NSString *updateSql = [NSString stringWithFormat:
                                   @"UPDATE tableName SET useNumber = '%d' WHERE name = '%@'",
                                   0,model.name];
            BOOL res = [_db executeUpdate:updateSql];
            if (!res) {
                NSLog(@"error when update db table");
            } else {
                NSLog(@"success to update db table");
            }
            [_db close];
            
        }
        
    }else{
    
        if ([_db open]) {
            NSUInteger newNumber = ++data.useNumber;
            NSString *updateSql = [NSString stringWithFormat:
                                   @"UPDATE tableName SET useNumber = '%lu' WHERE name = '%@'",
                                    newNumber ,model.name];
            BOOL res = [_db executeUpdate:updateSql];
            if (!res) {
                NSLog(@"error when update db table");
            } else {
                NSLog(@"success to update db table");
            }
            [_db close];
            
        }
    
    
    }



}


//根据课程名更新使用次数
-(void)updacycleWithModel:(CommenModel*)model{
    
   CommenModel * data  = [self fetchDataWithName:model.name];
    
        ++data.cycle;
        if ([_db open]) {
            NSString *updateSql = [NSString stringWithFormat:
                                   @"UPDATE tableName SET cycle = '%lu' WHERE useNumber = '%@'",
                                   (unsigned long)data.cycle,model.period];
            BOOL res = [_db executeUpdate:updateSql];
            if (!res) {
                NSLog(@"error when update db table");
            } else {
                NSLog(@"success to update db table");
            }
            [_db close];
            
        }
        
    //}
    
}

//根据课程名更新时间
-(void)updaTimeWithModel:(CommenModel*)model{
    
     NSDate *  senddate=[NSDate date];

    if ([_db open]) {
        NSString *updateSql = [NSString stringWithFormat:
                               @"UPDATE tableName SET lastTime = '%@' WHERE name = '%@'",
                               senddate,model.name];
        BOOL res = [_db executeUpdate:updateSql];
        if (!res) {
            NSLog(@"error when update db table");
        } else {
            NSLog(@"success to update db table");
        }
        [_db close];
        
    }
    
    //}
    
}


//读取数据
-(NSMutableArray *)fetchAllData
{
    NSMutableArray *videoDataArray = [NSMutableArray array];

    if ([_db open]) {
    NSString *sql = @"select * from tableName";
    FMResultSet *set = [_db executeQuery:sql];
    while ([set next]) {
        NSString *name = [set stringForColumn:@"name"];
        NSUInteger useNumber = [set longForColumn:@"useNumber"];
        NSDate *lastTime = (NSDate*)[set stringForColumn:@"lastTime"];
        NSUInteger cycle = [set longForColumn:@"cycle"];

        CommenModel *model = [[CommenModel alloc]init];
        model.name = name;
        model.useNumber = useNumber ;
        model.lastTime = lastTime;
        model.cycle = cycle;

        [videoDataArray addObject:model];
   }
        [_db close];
}
    return videoDataArray;


}


#pragma mark - 判断title是否已经存储过
- (BOOL)selectNewsTitle:(NSString*)name
{
    if ([_db open]) {
        NSString *sql = [NSString  stringWithFormat: @"select * from tableName where name = '%@'",name ];
        FMResultSet *set = [_db executeQuery:sql];
        while ([set next]) {
            NSString *nameString = [set stringForColumn:@"name"];
            if ([nameString isEqualToString:name]) {
                return YES;
            }
            
           
        }
        [_db close];
    }
    return NO;
}


//根据课程名，查找数据
-(CommenModel*)fetchDataWithName:(NSString*)name{
    CommenModel *model = [[CommenModel alloc]init];
    
    if ([_db open]) {
        NSString *sql = [NSString  stringWithFormat: @"select * from tableName where name = '%@'",name ];
        FMResultSet *set = [_db executeQuery:sql];
        while ([set next]) {
            NSUInteger useNumber = [set longForColumn:@"useNumber"];
            NSDate * lastTime = [set dateForColumn:@"lastTime"];
            NSUInteger cycle = [set longForColumn:@"cycle"];
            
            model.useNumber = useNumber;
            model.lastTime = lastTime;
            model.cycle = cycle;
        }
        [_db close];
    }
    return model;

}


//读取课程名
-(NSMutableArray *)fetchAllName
{
    NSMutableArray *nameArray = [NSMutableArray array];
    if ([_db open]) {
    NSString *sql = @"select * from tableName";
    FMResultSet *set = [_db executeQuery:sql];
    while ([set next]) {
        NSString *name = [set stringForColumn:@"name"];
        
        [nameArray addObject:name];
    }
        [_db close];
    }
    return nameArray;
}





@end






